﻿using NPOI.SS.UserModel;
using NPOI.SS.UserModel.Charts;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using suirui.ZhuMu.Model.Common;
using suirui.ZhuMu.Common;
using suirui.ZhuMu.Common.Utils;
using suirui.ZhuMu.Log;

namespace suirui.ZhuMu.Services
{
    public class ImportModelService
    {
        public WhiteListImportModel CheckData(string filePath, bool isEmail)
        {
            WhiteListImportModel result = new WhiteListImportModel();
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                try
                {
                    XSSFWorkbook workbook = new XSSFWorkbook(fs);  //根据EXCEL文件流初始化工作簿 
                    var dataSheet = workbook.GetSheetAt(0); //获取第一个sheet  
                    int rowCount = dataSheet.LastRowNum + 1; //总行数  
                    int rowFirst = dataSheet.FirstRowNum + 2;//去掉首行，因为首行为标题且第二行也是标题
                    #region 循环excel所有行,得到对应对象集合
                    for (int i = rowFirst; i < rowCount; i++)//循环行数据
                    {
                        IRow row = dataSheet.GetRow(i);
                        if (row != null)//不为空
                        {
                            result.Count++;
                            string userId = row.GetCell(0)?.ToString();
                            if (string.IsNullOrEmpty(userId?.Trim()))//内容空白行
                            {
                                result.NullRowIndex.Add(i + 1);
                            }
                            else
                            {
                                if ((!Util.IsEmail(userId) && isEmail) || (!Util.IsMobile(userId) && !isEmail))
                                {
                                    result.FailedList.Add(new WhiteListImportFailedRow() { RowIndex = i + 1, Content = userId, FailedType = WhiteListImportFailedReason.MatchFailed });
                                    continue;
                                }
                                else
                                {
                                    result.SuccessCount++;
                                }
                            }
                        }
                        else
                        {
                            result.NullRowIndex.Add(i + 1);
                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    DefaultLogFactory.Instance.Default_Loger.Error(ex);
                    return result;
                }
            }
            result.FailedCount = result.FailedList?.Count ?? 0;

            return result;
        }

        /// <summary>
        /// 将文件中的数据导入到白名单表中
        /// </summary>
        /// <param name="filePath">白名单位置</param>
        /// <param name="liveId">对应的直播ID</param>
        /// <param name="isDefaultPwd">是否需要导入ID</param>
        /// <returns></returns>
        public WhiteListImportModel ImportUserWhiteList(string filePath, long liveId)
        {
            bool isEmailList = false;
            bool isMobileList = false;
            DefaultLogFactory.Instance.Default_Loger.Info("ImportUserWhiteList");
            WhiteListImportModel result = null;
            string fileSuffix = filePath.Split('.')[filePath.Split('.').Length - 1];
            if (string.Equals(fileSuffix, "xlsx", StringComparison.OrdinalIgnoreCase))
            {
                result = new WhiteListImportModel();
                result.NullRowIndex = new List<int>();
                result.FailedList = new List<WhiteListImportFailedRow>();
                List<LiveViewerModel> datas = new List<LiveViewerModel>();
                using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))//读取文件流  
                {
                    try
                    {
                        XSSFWorkbook workbook = new XSSFWorkbook(fs);  //根据EXCEL文件流初始化工作簿 
                        var dataSheet = workbook.GetSheetAt(0); //获取第一个sheet  
                        int rowCount = dataSheet.LastRowNum + 1; //总行数  
                        int rowFirst = dataSheet.FirstRowNum + 2;//去掉首行，因为首行为标题且第二行也是标题
                        #region 循环excel所有行,得到对应对象集合
                        for (int i = rowFirst; i < rowCount; i++)//循环行数据
                        {
                            IRow row = dataSheet.GetRow(i);
                            if (row != null)//不为空
                            {
                                LiveViewerModel viewer = new LiveViewerModel();
                                string userId = row.GetCell(0)?.ToString();
                                if (string.IsNullOrEmpty(userId))//内容空白行
                                {
                                    result.NullRowIndex.Add(i + 1);
                                }
                                else
                                {
                                    if (Util.IsEmail(userId) && isEmailList)
                                    {
                                        viewer.Email = userId.Trim();
                                    }
                                    else if (Util.IsMobile(userId) && isMobileList)
                                    {
                                        viewer.Mobile = userId.Trim();
                                    }
                                    else//不符合验证规则
                                    {
                                        result.FailedList.Add(new WhiteListImportFailedRow() { RowIndex = i + 1, Content = userId, FailedType = WhiteListImportFailedReason.MatchFailed });
                                        continue;
                                    }
                                    if (!string.IsNullOrEmpty(viewer.Email))
                                    {
                                        viewer.Pwd = MD5Utils.GetMD5(row.GetCell(0).ToString());
                                    }
                                    viewer.RowIndex = i + 1;
                                    viewer.LiveId = liveId;
                                    datas.Add(viewer);
                                }
                            }
                            else
                            {
                                result.NullRowIndex.Add(i + 1);
                            }
                        }
                        #endregion

                        result.Count = rowCount - rowFirst;
                        if (datas?.Count > 0)
                        {
                            //SaveWhiteList(result, datas, liveId);
                        }
                        result.FailedCount = result.NullRowIndex.Count + result.FailedList.Count;
                    }
                    catch (Exception ex)
                    {
                        DefaultLogFactory.Instance.Default_Loger.Error(ex);
                        result = null;
                    }
                }
            }
            return result;
        }

    }
}
